<?php
 /**
 * class WeixinAction 处理微信接口的请求
 * @created on 2014/1/10
 * @last updated 2015/02/4 
 * @author yanqizheng
 */
namespace Api\Controller;
use Think\Controller;
use Spark\Util\HttpClient;
use Org\Net\UploadFile;

class WeixinController extends Controller {
    private $wx;
    private $xmlArr;
    private $responsestype = false;
    public function index(){
        $echoStr = $_GET["echostr"];
        if($echoStr){
            ob_clean();
            echo $echoStr;
            exit();
        }else{
            $this->clearBuffer();
            $this->xmlHandle();
        }
        exit();
    }
    private function xmlHandle(){
        $this->getXMLInfo();
        if ($this->xmlArr){
            $this->wx = M('wxuser')->where(['wxid'=>$this->xmlArr['ToUserName']])->find();
            if($this->wx){
                /* 后台得录入公众号信息才可以找到*/
                if($this->xmlArr['MsgType'] == 'text'){
                    $this->textHandle();
                }else if($this->xmlArr['MsgType'] == 'event'){
                    $this->eventHandle();
                }else{
                    $this->defaultResponse();
                }
            }
        }

        if($this->responsestype==false){
            $this->noResponse();
        }
    }

    private function textHandle(){
        $content = trim($this->xmlArr['Content']);
        //获取关键词消息
        $keywords = M('keyword')->where(['token'=>$this->wx['token']])->select();
        foreach($keywords as $info){
            if($this->responsestype==false){
                if($info['is_strict']==1){
                    $inKeyword = $info['keyword']==$content ? true : false;
                }else{
                    $inKeyword = strstr($content,$info['keyword']) ? true : false;
                }
                if($inKeyword){
                    if($info['module']=='Img'){
                        $this->imgResponse($info);
                    }
                    if($info['module']=='Text'){
                        $this->textResponse($info);
                    }
                }
            }
        }
        //回复默认消息
        if($this->responsestype==false){
            $this->defaultResponse();
        }
    }
    /*事件处理*/
        private function eventHandle()
        {
            $Event = $this->xmlArr['Event'];
            if($Event == 'subscribe'){
                $EventKey = $this->xmlArr['EventKey'];
                M('wxuser')->field('wxfans')->where(['token'=>$this->wx['token']])->setInc('wxfans');
                $this->getSubscribeInfo();//update TABLE wechat_user
                if(!empty($EventKey)){
                    $EventKey = str_replace("qrscene_","",$EventKey);
                    $this->updateUserInfo($EventKey);//update TABLE juejin_users
                    $this->areplyResponse();
                }else{
                    $this->updateUserInfo("");//update TABLE juejin_users
                    $this->areplyResponse();
                }
                $this->echoBuffer();
                $this->createMediaId();//create qrcode img
            }elseif ($Event == 'unsubscribe'){
                M('wxuser')->field('wxfans')->where(['token'=>$this->wx['token']])->setDec('wxfans');
                $this->noResponse();
            }elseif($Event == 'SCAN' || $Event == 'scan'){
                $EventKey = $this->xmlArr['EventKey'];
                $Ticket = $this->xmlArr['Ticket'];
                $this->updateUserInfo($EventKey);
                $this->noResponse();
            }elseif($Event == 'CLICK'){
                $this->updateUserInfo();
                $con = $this->xmlArr['EventKey'];
                if( $con == "invitejpg" )
                {
                    $this->invite();
                }
            }else{
                $this->noResponse();
            }
        }

    private function getXMLInfo(){
        ob_clean();
        $xmlStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if(!empty($xmlStr)){
            $this->xmlArr = json_decode(json_encode(simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA)),TRUE);
            $this->xmlArr['Time'] = time();
        }else{
            return false;
        }
    }
   


    private function getSubscribeInfo(){
        $util = new \Spark\Wechat\WechatUtil($this->wx['appid'],$this->wx['appsecret']);
        $userinfo = $util->getUser($this->xmlArr['FromUserName']);
        $data['token'] =$this->wx['token'];
        $data['open_id'] = $this->xmlArr['FromUserName'];
        $data['wechat_name'] = $userinfo->nickname;
        $data['sex'] = $userinfo->sex;
        $data['language'] = $userinfo->language;
        $data['country'] = $userinfo->country;
        $data['province'] = $userinfo->province;
        $data['headimgurl'] = substr($userinfo->headimgurl,0,-1);
        $data['subscribe_time'] = $userinfo->subscribe_time;
        $data['subscribe'] = $userinfo->subscribe;
        $data['update_time'] = time();
        $isUserCreate = M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        if($isUserCreate){
            M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->save($data);
        }else{
            M('wechat_user')->add($data);
        }
    }


    private function updateUserInfo($parentid){
        /*添加或者更新用户信息时
        1、检查是否有shareid。2、检查是否是旧用户*/
        $parentInfo = M('juejin_users')->where(['id'=>$parentid])->find();
        $token = "";
        $dateary = "";
        //$wx = M('wxuser')->where(['wxid'=>$this->xmlArr['ToUserName']])->find();
        /*2.检查是否是旧用户*/
        $userinfo = M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        $wechatuser = M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        if( $userinfo )
        {
            /*是旧用户*/
            $date['headimgurl'] = $wechatuser['headimgurl'];
            if($parentInfo){
               $date['token'] = $parentInfo['token'];
            }else{
               $date['token'] = $this->wx['token'];
            }
            M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->save( $date );

        }else{
            /*add */
            $dateary['open_id'] = $this->xmlArr['FromUserName'];
            $dateary['create_time'] = time();
            $dateary['last_login_time'] = "";
            $dateary['last_login_ip'] = "";
            $dateary['shareid'] = $parentid;
            $dateary['headimgurl'] = $wechatuser['headimgurl'];
            if($parentInfo){
               $dateary['token'] = $parentInfo['token'];
            }else{
               $dateary['token'] = $this->wx['token'];
            }
            if($parentInfo){
               $dateary['token'] = $parentInfo['token'];
            }else{
               $dateary['token'] = $this->wx['token'];
            }
            $newid = M('juejin_users')->add( $dateary );


            if( $parentid )
            {
                /*需要给上级+1分*/
                M('juejin_users')->where(['id'=>$parentid])->setInc('integral',1);

                $log['userid'] = $parentid;
                $log['num'] = 1;
                $log['date'] = time();
                $log['note'] = '获得粉丝';
                $log['createtime'] = time();
                M("juejin_integral_log")->add($log);

            }
        }
    }

    private function imgResponse($info){
        $resContent = M('Img')->where(['id'=>$info['pid']])->find();
        $resContent['url'] = $resContent['url']=='' ? $resContent['info'] : $resContent['url'];
        $resultStr = sprintf($this->newsTpl,$this->xmlArr['FromUserName'],$this->xmlArr['ToUserName'],$this->xmlArr['Time'],'news',1,
            $resContent['title'],$resContent['text'],$resContent['pic'],$resContent['url']);
        echo $resultStr;
        $this->responsestype=true;
    }
    private function textResponse($info){
        $resContent = M('Text')->where(['id'=>$info['pid']])->find();
        $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $resContent['text']);
        echo $resultStr;
        $this->responsestype=true;
    }
    private function defaultResponse(){
        $resContent = M('other')->where(['token'=>$this->wx['token']])->find();
        $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $resContent['keyword']);
        echo $resultStr;
        $this->responsestype=true;
    }
    /*关注回复*/
    private function areplyResponse(){
        $idindex = 0;
        $userinfo = M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        $wechatUser = M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->field('wechat_name')->find();
        $idindex = intval( $userinfo['id'] );
        $resContent = M('areply')->where(['token'=>$this->wx['token']])->find();
        $responseContent = $resContent['keyword'];
        $responseContent = str_replace("[wechatname]",$wechatUser["wechat_name"],$responseContent);
        $responseContent = str_replace("[id]",$idindex,$responseContent);
        $responseContent = str_replace("\r\n","\n",$responseContent);
        //$in="终于等到你".$wechatUser["wechat_name"]."！你是第".$idindex."位发现我们的智者！\n本次积分兑换活动是【完全免费，全国包邮】，您无需支付任何费用！获取积分途径：\n1、点击菜单栏--我的邀请码。\n2、保存海报分享朋友圈，邀请好友识码关注，成功邀请一位获得1积分，累计38分点击兑换！\n3、兑换后填写收货人电话和地址，在七个工作日内我们将发货给您！";
        $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $responseContent);
        echo $resultStr;
        $this->responsestype=true;

    }
    private function msgResponse($msg){
        $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $msg);
        echo $resultStr;
        $this->responsestype=true;
    }
    private function noResponse(){
        echo 'success';
        $this->responsestype=true;
        exit();
    }
    private function invite(){
        $userinfo = M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        if( $userinfo['media_id_status'] == '1' ){
            //file_put_contents("beifen.txt", "图片正在创建，请稍后再试", FILE_APPEND );
            //$this->msgResponse("图片正在创建，请稍后再试");
            echo "success";
        }else{
            if($userinfo['media_expire'] < time()){
                //$this->msgResponse("正在创建图片，请稍后再试");
                $media_id = $this->createMediaId();
            }else{
                $media_id = $userinfo['media_id'];
            }

            if($media_id){
               $resultStr = sprintf($this->imgTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'image', $media_id);
               echo $resultStr;
            }else{
               echo "success";
            }
        }
        exit();
    }
    private function clearBuffer(){
        ob_clean();
        ob_end_flush();
        ob_start();
    }
    private function echoBuffer(){
        header("Content-Type: text/html;charset=utf-8");
        header("Connection: close");
        header('Content-Length: '. ob_get_length());
        ob_flush();
        flush();
    }
    private function createMediaId(){
        //$this->echoBuffer();
        //start mk pic status
        $data['media_id_status'] = 1;
        M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->save($data);

        $util = new \Spark\Wechat\WechatUtil($this->wx['appid'],$this->wx['appsecret']);
        $userinfo = M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        $media_id = "";

        //二维码
        $url = $util->getQrcodeUrl(intval($userinfo['id']));

        $TMP_DIR = __ROOT__.'/Uploads/Crm/';
        $bg = C('site_url').'/Uploads/Crm/create_qrcode_img.png';

        $logo  = imagecreatefromstring(file_get_contents($url));

        if ($logo !== FALSE) {
            $QR = imagecreatefromstring(file_get_contents($bg));

            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            imagecopyresized($QR, $logo, 46, 92, 0, 0, 176, 176, $logo_width, $logo_height);
            /*$headimg  = imagecreatefromstring( file_get_contents(  $userinfo['headimgurl']."64" ));
            $head_width = imagesx($headimg);//logo图片宽度
            $head_height = imagesy($headimg);//logo图片高度
            $head_qr_width = $QR_width / 5;
            $scale = $head_width/$head_qr_width;
            $head_qr_height = $head_height/$scale;
            $from_width = ($QR_width - $head_qr_width) / 2;

            if ($headimg !== FALSE) {
                imagecopyresized($QR, $headimg, 487/2, 47/2, 0, 0, 117/2, 118/2, $head_width, $head_height);
            }*/
        }

        $filename = md5($scene['scene_id']).'.png';
        $imagresult = ImagePng($QR, $TMP_DIR.$filename);

        $PNG_WEB_BASE_URL = $_SERVER['DOCUMENT_ROOT'].'/Uploads/Crm/'.$filename;

        /*把图片上传到临时素材库start*/
        $accesstoken = $util->getAccessToken( $this->wx["appId"], $this->wx["appsecret"] );
        $wximgurl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$accesstoken."&type=image";

        if(class_exists('\CURLFile')){
            $para['media'] = new \CURLFile(realpath($PNG_WEB_BASE_URL));
        }else{
            $para['media'] = '@'.realpath($PNG_WEB_BASE_URL);

        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$wximgurl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $para );
        $result = curl_exec($ch);
        curl_close ($ch);

        if( $result ){
           if (curl_errno() == 0){
               $result = json_decode($result, true);
               if( $result['media_id'] ){
                   $data['media_id'] = $result['media_id'];
                   $data['media_expire'] = 3*24*3600+time();
                   $data['media_id_status'] = 0;
                   M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->save($data);
                   return $result['media_id'];
               }
           }
        }
    }



   



    //$url ： 接口地址 $param ： 上传数据
    private function http_post($url,$param){
         $oCurl = curl_init();
         if(stripos($url,"https://")!==FALSE){
         curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
         }
         $strPOST = $param;
         curl_setopt($oCurl, CURLOPT_URL, $url);
         curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
         curl_setopt($oCurl, CURLOPT_POST,true);
         curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
         $sContent = curl_exec($oCurl);
         $aStatus = curl_getinfo($oCurl);
         curl_close($oCurl);
         if(intval($aStatus["http_code"])==200){
                return $sContent;
         }else{
                 return false;
         }
     }



    private $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
        </xml>";
    private $newsTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
                <item>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                <PicUrl><![CDATA[%s]]></PicUrl>
                <Url><![CDATA[%s]]></Url>
                </item>
            </Articles>
        </xml>";

    private $imgTpl = "<xml>
                       <ToUserName><![CDATA[%s]]></ToUserName>
                       <FromUserName><![CDATA[%s]]></FromUserName>
                       <CreateTime>%s</CreateTime>
                       <MsgType><![CDATA[%s]]></MsgType>
                       <Image>
                       <MediaId><![CDATA[%s]]></MediaId>
                       </Image>
                       </xml>";


}
?>